package com.exam.controller;

import com.exam.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/jwt")
public class JwtController {
    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    /**
     * 添加Cookie，生成并返回JWT Token
     *
     * @param key      键名
     * @param value    键值
     * @param response 用于添加Cookie
     * @return 返回生成的JWT Token
     */
    @RequestMapping("add")
    public String add(String key, String value, HttpServletResponse response) {
        Map<String, Object> infoMap = new HashMap<>();
        infoMap.put(key, value);
        String token = JwtUtil.getToken(infoMap, 30);
        Cookie cookie = new Cookie("token", token);
        cookie.setPath("/");
        response.addCookie(cookie);
        return token;
    }

    /**
     * 解析Cookie中的JWT Token，并返回指定键名对应的键值
     *
     * @param key     键名
     * @param token   JWT Token
     * @param request 用于获取Cookie
     * @return 返回指定键名对应的键值
     */
    @RequestMapping("parse")
    public String parse(String key, String token, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        String tokenFromCookie = null;
        for (Cookie cookie : cookies) {
            if ("token".equals(cookie.getName())) {
                tokenFromCookie = cookie.getValue();
            }
        }
        return JwtUtil.parse(tokenFromCookie,key);
    }
}
